package org.lxy.controller;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.lxy.config.OSSClientConfig;
import org.lxy.domain.RecycleGoodsEntity;
import org.lxy.domain.RecyclePointEntity;
import org.lxy.domain.UserInfoEntity;
import org.lxy.domain.constant.CoreConstant;
import org.lxy.service.RecycleGoodsService;
import org.lxy.utils.CoreUtils;
import org.lxy.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/recyclegoods")
public class RecycleGoodsController extends BaseController {

    @Autowired
    private RecycleGoodsService recycleGoodsService;
    @Autowired
    private OSSClientConfig ossClientUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public ModelAndView list(@RequestParam Map<String, Object> params) {
        PageUtils page = recycleGoodsService.queryPage(params);

        return null;
    }

    @RequestMapping("delete")
    @ResponseBody
    public Integer delete(String ids) {
        return recycleGoodsService.removeByIds(Arrays.asList(ids.split(","))) ? 1 : 0;
    }


    @RequestMapping("edit")
    public void edit(MultipartFile tupian, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        String op = "";
        boolean tag = true;
        String s = ossClientUtil.uploadFile2OSS(tupian);
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        String dizhi = "";
        int duihuanjifen = 0;
        int huishoudianid = 0;
        int huisoufangshi = 0;
        int id = 0;
        String jieshao = "";
        int leixingid = 0;
        String mingcheng = "";
        String shangmenhuishoushijian = "";
        int xuyaojifen = 0;
        String zhuangtai = "";
        String huishoufangshi = "";
        String fname = "";
        String xiangqing = "";
        dizhi = request.getParameter("dizhi");
        huishoudianid = Integer.parseInt(request.getParameter("huishoudianid"));
        huishoufangshi = request.getParameter("huishoufangshi");
        jieshao = request.getParameter("jieshao");
        leixingid = Integer.parseInt(request.getParameter("leixingid"));
        mingcheng = request.getParameter("mingcheng");
        shangmenhuishoushijian = request.getParameter("shangmenhuishouishijian");
        id = Integer.parseInt(request.getParameter("id"));
        RecycleGoodsEntity entity = new RecycleGoodsEntity();
        UserInfoEntity account = (UserInfoEntity) request.getSession().getAttribute("Account");
        PrintWriter out = response.getWriter();
        if (account == null) {
            out.write("<script>window.top.location.href='/login';</script>");
            return;
        }
        if (id > 0) {
            entity = CoreUtils.recycleGoodsService.getById(id);
        } else {
            entity.setId(0);
            entity.setImg("");
            entity.setStatus("0");
        }
        entity.setAddress(dizhi);
        if (StringUtils.isNotBlank(s)){
            entity.setImg(s);
        }
        entity.setChangePoints(duihuanjifen);
        entity.setRecyclePointId(huishoudianid);
        entity.setRecycleMethod(huishoufangshi);
        entity.setId(id);
        entity.setInfo(jieshao);
        entity.setTypeId(leixingid);
        entity.setName(mingcheng);
        entity.setOnSiteRecycleTime(shangmenhuishoushijian);
        entity.setUserId(account.getId());
        entity.setRecyclePoints(xuyaojifen);
        entity.setStatus("兑换中");
        if (!fname.isEmpty()) {
            entity.setImg(fname);
        }

        tag = false;
        if (entity.getId() > 0) {
            tag = CoreUtils.recycleGoodsService.updateById(entity);
        } else {
            tag = CoreUtils.recycleGoodsService.save(entity);
            account.setPoints(account.getPoints() + entity.getRecyclePoints());
            CoreUtils.userInfoService.updateById(account);
            request.getSession().setAttribute("Account", account);
        }
        if (tag) {
            out.write(
                    "<script>alert('操作成功!');window.parent.location.href='../recyclegoods/operation?op=List&type=2';</script>");
        } else {
            out.write("<script>alert('操作失败!');</script>");
        }


    }


    @RequestMapping("operation")
    public ModelAndView operation(Long id, String
            op, @RequestParam(defaultValue = CoreConstant.LIST) String type) {
        ModelAndView modelAndView = new ModelAndView();
        if (CoreConstant.LIST.equals(op)) {
            boolean tag = CoreConstant.ONE.equals(type);
            RecycleGoodsEntity recycleGoodsEntity = new RecycleGoodsEntity();
            if (tag) {
                recycleGoodsEntity.setRecycleMethod("上门回收");
                List<RecycleGoodsEntity> list = recycleGoodsService.queryList(recycleGoodsEntity);
                modelAndView.addObject("list", list);
                modelAndView.setViewName("/huishouwupin/shangmenhuishouwupinlist");

            } else {
                recycleGoodsEntity.setRecycleMethod("回收点回收");
                modelAndView.addObject("list", recycleGoodsService.queryList(recycleGoodsEntity));
                modelAndView.setViewName("/huishouwupin/huishouwupinlist");
            }
        } else if (CoreConstant.ADD.equals(op)) {
            RecycleGoodsEntity entity = new RecycleGoodsEntity();
            modelAndView.addObject("entitys", entity);
            modelAndView.setViewName("/huishouwupin/huishouwupinEdit");
        } else if (CoreConstant.EDIT.equals(op)) {
            RecycleGoodsEntity entity = recycleGoodsService.getById(id);
            modelAndView.addObject("entitys", entity);
            modelAndView.setViewName("/huishouwupin/huishouwupinEdit");
        }
        return modelAndView;
    }


    @RequestMapping("editGoods")
    public void editGoods(MultipartFile tupian, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        String dizhi = "";
        int duihuanjifen = 0;
        int huishoudianid = 0;
        int huisoufangshi = 0;
        int id = 0;
        String jieshao = "";
        int leixingid = 0;
        String mingcheng = "";
        String shangmenhuishoushijian = "";
        int xuyaojifen = 0;
        String zhuangtai = "";
        String huishoufangshi = "";
        String fname = "";
        String xiangqing = "";
        dizhi = request.getParameter("dizhi");
        xuyaojifen = StringUtils.isNotBlank(request.getParameter("xuyaojifen"))?Integer.parseInt(request.getParameter("xuyaojifen")):0;
        huishoudianid = StringUtils.isNotBlank(request.getParameter("huishoudianid"))?Integer.parseInt(request.getParameter("huishoudianid")):0;
        huishoufangshi = request.getParameter("huishoufangshi");
        jieshao = request.getParameter("jieshao");
        leixingid = StringUtils.isNotBlank(request.getParameter("leixingid"))?Integer.parseInt(request.getParameter("leixingid")):0;
        mingcheng = request.getParameter("mingcheng");
        shangmenhuishoushijian = request.getParameter("shangmenhuishouishijian");
        id = StringUtils.isNotBlank(request.getParameter("id"))?Integer.parseInt(request.getParameter("id")):0;
        RecycleGoodsEntity entity = new RecycleGoodsEntity();
        RecycleGoodsService service = CoreUtils.recycleGoodsService;
        UserInfoEntity account = (UserInfoEntity) request.getSession().getAttribute("Account");
        entity.setAddress(dizhi);
        if (huishoudianid > 0){
            RecyclePointEntity recyclePointEntity = CoreUtils.recyclePointService.getById(huishoudianid);
            if (Objects.nonNull(recyclePointEntity)){
                entity.setAddress(recyclePointEntity.getAddress());
            }
        }
        if (account == null) {
            out.write("<script>window.top.location.href='/login';</script>");
            return;
        }
        if (id > 0) {
            entity = service.getById(id);
        } else {
            entity.setId(0);
            entity.setImg("");
            entity.setStatus("0");
        }
        String s = ossClientUtil.uploadFile2OSS(tupian);
        if (StringUtils.isNotBlank(s)){
            entity.setImg(s);
        }
        entity.setChangePoints(duihuanjifen);
        entity.setRecyclePointId(huishoudianid);
        entity.setRecycleMethod(huishoufangshi);
        entity.setId(id);
        entity.setInfo(jieshao);
        entity.setTypeId(leixingid);
        entity.setName(mingcheng);
        entity.setOnSiteRecycleTime(shangmenhuishoushijian);
        entity.setUserId(account.getId());
        entity.setRecyclePoints(xuyaojifen);
        entity.setStatus("待审核");
        if (!fname.isEmpty()) {
            entity.setImg(fname);
        }

        boolean tag = false;
        if (entity.getId() > 0) {
            tag = service.updateById(entity);
        } else {
            tag = service.save(entity);
            account.setPoints(account.getPoints() + entity.getRecyclePoints());
            CoreUtils.userInfoService.updateById(account);
            request.getSession().setAttribute("Account", account);
        }
        System.out.println("回收商品:" + JSONObject.toJSONString(entity));
        if (tag) {
            if (huishoufangshi.equals("回收点回收")) {
                out.write("<script>alert('操作成功!');window.location.href='/huishoudianhuishou"
                        + "';</script>");
            } else {
                out.write("<script>alert('操作成功!');window.location.href='/shangmenhuishou"
                        + "';</script>");
            }

        } else {
            out.write("<script>alert('操作失败!');</script>");

        }
    }

    /*  *//**
     * 信息
     *//*
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		RecycleGoodsEntity recycleGoods = recycleGoodsService.getById(id);

        return R.ok().put("recycleGoods", recycleGoods);
    }

    *//**
     * 保存
     *//*
    @RequestMapping("/save")
    public R save(@RequestBody RecycleGoodsEntity recycleGoods){
		recycleGoodsService.save(recycleGoods);

        return R.ok();
    }

    *//**
     * 修改
     *//*
    @RequestMapping("/update")
    public R update(@RequestBody RecycleGoodsEntity recycleGoods){
		recycleGoodsService.updateById(recycleGoods);

        return R.ok();
    }

    *//**
     * 删除
     *//*
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		recycleGoodsService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }*/

}
